import { Modal, Form, Input, Select, Upload, Button, message, InputNumber } from 'antd'
import {
  UploadOutlined
} from '@ant-design/icons'
import { apiInterceptors, createTenant, getTenantById, updateTenant, uploadFile } from '@/client/api';
import React, { useEffect, useState } from 'react'
import {record} from "zod";
import {nameRule} from "../../../utils/validationRules";

const TenantModal = ({ handleType, isModalOpen, setModal, tenantId, successCall }: any) => {
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };
  const [userForm] = Form.useForm();
  const submitHandle = async () => {
    try {
      const values = await userForm.validateFields();
      // values.status = values.status ? '1' : '0'
      if (handleType === 'edit') {
        values.id = tenantId
        const [err] = await apiInterceptors(updateTenant(values))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      if (handleType === 'add') {
        // values.logo = 'https://tse3-mm.cn.bing.net/th/id/OIP-C.dCmg3nt2SG6FlC74naPU4gHaHa?rs=1&pid=ImgDetMain'
        const [err] = await apiInterceptors(createTenant(values))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      setModal(false)
      successCall()
      resetForm()
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const cancelHandle = () => {
    setModal(false)
    resetForm()
  }
  const handleChange = () => {

  }
  const resetForm = () => {
    userForm.resetFields()
  }
  const getTenantInfo = async () => {
    const [_, tenantInfo] = await apiInterceptors(getTenantById(tenantId))
    userForm.setFieldsValue(tenantInfo)
  }
  const uploadLogo = async (e) => {
    const [err] = await apiInterceptors(uploadFile({ files: e.file, id: tenantId }))
    if (!err) {
      e.onSuccess()
    }
  }
  useEffect(() => {
    if (handleType === 'edit') {
      getTenantInfo()
    }
  },[])
  return (<>
    <Modal
      title={handleType === 'add' ? '新增租户' : '修改租户'}
      open={isModalOpen}
      onOk={submitHandle} onCancel={cancelHandle}
      width={800}
    >
      <Form {...formItemLayout} form={userForm} initialValues={{app_num: 1}}>
        <Form.Item label="租户名称" name="name" rules={[{ required: true, message: '请输入租户名称' }, nameRule]}>
          <Input />
        </Form.Item>
        {
          handleType === 'edit' &&
          <Form.Item label="租户LOGO" name="">
              <Upload customRequest={uploadLogo} maxCount={1} accept="image/*">
                  <Button icon={<UploadOutlined />}>点击上传</Button>
              </Upload>
          </Form.Item>
        }
        <Form.Item label="域名" name="domain" rules={[{ required: true, message: '请输入域名' }, { pattern: /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i, message: '请输入正确的域名'}]}>
          <Input />
        </Form.Item>
{/*        <Form.Item label="API 令牌" name="app_key">
          <Input disabled />
        </Form.Item>*/}
        <Form.Item label="App支持数" name="app_num" rules={[{required: true, message: '请输入App支持数'}]}>
          <InputNumber min={1} precision={0}/>
        </Form.Item>
        <Form.Item label="联系人姓名" name="contact" rules={[nameRule]}>
          <Input />
        </Form.Item>
        <Form.Item label="联系人邮箱" name="email" validateTrigger="onBlur" rules={[
            { pattern: /^\w+@[a-z0-9]+\.[a-z]{2,4}$/, message: '请输入正确的邮箱' }
        ]}>
          <Input />
        </Form.Item>
{/*        <Form.Item label="租户管理员" name="admin_ids">
          <Select
            defaultValue="lucy"
            onChange={handleChange}
            options={[
              { value: 'jack', label: 'Jack' },
              { value: 'lucy', label: 'Lucy' },
              { value: 'Yiminghe', label: 'yiminghe' },
              { value: 'disabled', label: 'Disabled', disabled: true },
            ]}
          />
        </Form.Item>*/}
        <Form.Item label="联系电话" name="phone" validateTrigger="onBlur" rules={[
          { required: true, message: '请输入联系电话' },
          { pattern: /^1[3|4|5|7|8][0-9]{9}$/, message: '请输入正确的联系电话' }
        ]}>
          <Input />
        </Form.Item>
{/*        <Form.Item label="销售合同" name="sales_contract">
          <Upload>
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Form.Item>*/}
        <Form.Item label="状态" name="status">
          <Select
            placeholder="请选择状态"
            options={[
              { value: '1', label: '启用' },
              { value: '0', label: '禁用' },
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  </>)
}

export default TenantModal
